<template>
  <Drawer :title="title">
    <BaseForm>
      <template #coordinate>
        <div class="flex w-full">
          <a-input
            placeholder="请选择小区所在位置"
            :disabled="true"
            :value="coordinateStr"
          />
          <Button class="ml-3" type="primary" @click="openMap">点击选择</Button>
        </div>
      </template>
    </BaseForm>
    <MapModel
      ref="mapModelRef"
      v-model="coordinateStr"
      @changeType="isHandlePoint = false"
    />
  </Drawer>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { querySave, queryUpdate } from '../data/api';
import { drawerFormSchema, handleId, idKey } from '../data/options';
import { message, Button, Input } from 'ant-design-vue';
import MapModel from './mapModel.vue';
import { useThrottleFn } from '@vueuse/core';

const emit = defineEmits(['success']);
const mapModelRef = ref<any>('');
const title = computed(() => {
  return `${handleId.value ? '编辑' : '新增'}微馆`;
});
const coordinateStr = ref<any>('');
const isHandlePoint = ref<any>(false);

// 抽屉提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  if (!values[idKey.value]) delete values[idKey.value];
  let query = values[idKey.value] ? queryUpdate : querySave;
  let res: any = await query({ ...values });
  message.success(res.message);
  onSucClose();
}, 1000);

// 抽屉配置
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      let data = drawerApi.getData();
      const { lat, lng } = data;
      if (lat && lng) {
        const val = `${lat},${lng}`;
        coordinateStr.value = val;
        data.coordinate = val;
      }
      handleId.value = data[idKey.value] || '';
      formApi.setValues({ ...data });
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    labelWidth: 150,
    componentProps: {
      class: 'w-full',
    },
  },
});

const onSucClose = () => {
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = () => {
  console.log('coordinateStr', coordinateStr.value);
  formApi.submitForm();
};

//监听数据并赋值
watch(
  () => coordinateStr.value,
  (val) => {
    if (isHandlePoint.value) {
      console.log('coordinateStr', val);
      let pointArr = val.split(',');
      formApi.setFieldValue('lat', pointArr[0]);
      formApi.setFieldValue('lng', pointArr[1]);
      formApi.setFieldValue('coordinate', val);
    }
  },
);

// 打开地图
const openMap = () => {
  console.log('openMap');
  mapModelRef.value?.open(coordinateStr.value);
  isHandlePoint.value = true;
};
</script>

<style lang="scss" scoped></style>
